﻿using PdfChartHelper.Models;
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PdfChartHelper.Writer
{
    public class HistogramWriter
    {
        public static PdfDocument RenderHistogram(int X, int Y, int Width, int Hight,
           List<Histogram> list)
        {
            PdfDocument doc = new PdfDocument();

            PdfPage page = new PdfPage(doc);

            XGraphics graphics = XGraphics.FromPdfPage(page);

            //Step-One需要根据最大值来确定刻度是多少

            double max = list.Max(item => item.num);

            //如果最大值可以被5整除就把最大值作为最大刻度，假设为1，其他的长度根据和最大值的比例来决定

            int Native = ((int)max);

            int MaxScale = 0;

            if (Native % 5 == 0)
                MaxScale = Native;
            else
            {
                //如果不能被整除，就设置最近的可以被5整除的数作为上限刻度
                MaxScale = (Native / 5 + 1) * 5;
            }

            List<int> scales = new List<int>() { MaxScale / 5, MaxScale / 5 * 2, MaxScale / 5 * 3, MaxScale / 5 * 4, MaxScale }; scales.Sort();

            //先画一个坐标轴
            //graphics.DrawLine(new XPen(XBrushes.Aqua,1), 10, 10, 10, 150); //Y
            //graphics.DrawLine(new XPen(XBrushes.Aqua,1), 5, 140, 180, 140); //X

            graphics.DrawLine(new XPen(XBrushes.Aqua, 1), X, Y, X, Y + Hight + 5); //Y
            graphics.DrawLine(new XPen(XBrushes.Aqua, 1), X - 5, Y + Hight, X + Width, Y + Hight); //X


            //再画刻度线,平行于X轴
           

            int temp = Hight / 5;
            scales.ForEach(item => {
                graphics.DrawLine(new XPen(XBrushes.Azure, 0.4), X - 2, Hight + Y - temp, X + Width, Hight + Y - temp);
                graphics.DrawString(item.ToString(), new XFont("Arial", 6, XFontStyle.Regular), XBrushes.RoyalBlue, X - 8, Hight + Y - temp - 5);
                temp += Hight / 5;
            });

            //填充柱状图，并列出DESC

            
            int space = Width / list.Count / 2;

            double tempSpace = 0;
            list.ForEach(item => {

                double Real_length = (item.num / MaxScale) * Hight;

                graphics.DrawRectangle(item.color, 10 + space / 2 + tempSpace + X, Hight + Y, space, -1 * Real_length);
                graphics.DrawString(item.desc, new XFont("Arial", 6, XFontStyle.Regular), XBrushes.Black, 10 + space / 2 + tempSpace + X, Hight + Y + 5);

                tempSpace += space * 2;
            });



            graphics.Save();

            doc.AddPage(page);

            return doc;
        }

    }
}
